from es import exists, getplayersteamid
from cmdlib import registerSayCommand, unregisterSayCommand
from superdice.superdice import rollStrings
from superdice.libs.diceConfigs import configFile
from superdice.libs.playerStrings import stringsManager
from superdice.libs.dataManager import dataManager

def mostCallback(userid, args):
    steamid = getplayersteamid(userid)
    if not steamid in database:
        database[steamid] = {}

    if database[steamid]:
        strings.tellString(userid, 'mostrolled', {'roll':rollStrings.getString(userid, max(database[steamid], key=lambda roll: database[steamid][roll]) + ':name', {})})

    else:
        strings.tellString(userid, 'nomost', {})

def player_roll_success(ev):
    steamid = ev['es_steamid']
    roll = ev['roll']
    if not steamid in database:
        database[steamid] = {}

    if not roll in database[steamid]:
        database[steamid][roll] = 0

    database[steamid][roll] += 1

def round_end(ev):
    database.saveDatabase()

def unload():
    database.saveDatabase()
    for command in mostCommands:
        if not exists('saycommand', command):
            continue
        unregisterSayCommand(command)

configData = configFile('addon_mostrolled')
mostCommands = str(configData.cvar('superdice_cfg_mostrolled_mostcommands', '!mostrolled,mostrolled', 'What commands are used?')).split(',')
configData.write()
configData.execute()

for command in mostCommands:
    if exists('saycommand', command):
        continue
    registerSayCommand(command, mostCallback, 'MostRolled the dice commands for players used by SuperDice.')

database = dataManager('addon_mostrolled')

strings = stringsManager('addon_mostrolled')
